package com.dongway.netcondition.socketToBox;

import java.io.InputStream;
import java.net.Socket;


public class ThreadSocket implements Runnable {

	private Socket socket;
	private Integer id;
	private  boolean end=true;
	public ThreadSocket(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		
		try {
			// 若Socket不断开，那么服务器就一直接收盒子发送过来的信息。
			while (end) {
				
	    	
				InputStream in = socket.getInputStream();
				byte[] b = new byte[1024];
				int len = in.read(b);							
				switch (len) {
				case 224:
					System.out.println("查询设备监控指令：" + len);
					SocketContent.getInfo(id).setIpPhone(b);
					break;
				case 156:
					System.out.println("查询设备网卡指令：" + len);
					SocketContent.getInfo(id).setNetInfo(b);
					break;
				case 48:
					System.out.println("查询设备是否监控信息指令：" + len);
					SocketContent.getInfo(id).setIpListener(b);
					break;
				case 24:
					Integer id = getDevId(b);
					String str = new String(b, 0, len);
					str = str.substring(9, 16); // 获取监控涉笔的信息
					// 设备ID监控信息存储到一个Map 中
					SocketContent.getInstance().putDev(id, str);
					// 存储当前设备ID以及相应的Socket
					SocketContent.getInstance().online(id, socket, str);
					break;
					
				case 23:
					
					Integer id1 = getDevId1(b);
					String str1 = new String(b, 0, len);
					str1 = str1.substring(9, 16); // 获取监控涉笔的信息
					// 设备ID监控信息存储到一个Map 中
					SocketContent.getInstance().putDev(id1, str1);
					// 存储当前设备ID以及相应的Socket
					SocketContent.getInstance().online(id1, socket, str1);
					
				case -1:  end=false;
				             break;
				default:										
					/*
					 * 对接收的进行进行预处理 while (len != 24) { in =
					 * socket.getInputStream(); b = new byte[1024]; len =
					 * in.read(b); }
					 */
					break;
				}

			}

		} catch (Exception e) {
			 end=false;
			
		}

	}

	private Integer getDevId(byte[] b) {
		String str = new String(b, 0, 24);
		
		Integer id = str.substring(22, 23).charAt(0) - 48; // 获取设备ID
		this.id=id;
		return id;
	}
	
	private Integer getDevId1(byte[] b) {
		String str = new String(b, 0, 23);
		
		Integer id = str.substring(21, 22).charAt(0) - 48; // 获取设备ID
		this.id=id;
		return id;
	}
	
	
}
